<template>
    <div class="jianzhan-content">
        <Crumb :name="$t('invoice.invoice')"/>
        <Search>
            <el-date-picker size="small"
                            :start-placeholder="$t('invoice.startTime')"
                            :end-placeholder="$t('invoice.endTime')"
                            type="datetimerange"
                            v-model="time"
                            value-format="yyyy-MM-dd"> </el-date-picker>
            <el-input v-model.number="coefficient"
                      :placeholder="$t('invoice.factor')"
                      v-if="urlAvailible('sale-factor')"
                      size="small"
                      class="input"></el-input>
            <el-select
                    v-model="customer"
                    :placeholder="$t('invoice.customer')"
                    class="input"
                    size="small"
                    clearable>
                <el-option v-for="item in customerList" :value="item.customerName" :label="item.customerName"
                           :key="item.id"></el-option>
            </el-select>
            <el-button icon="el-icon-search" type="primary" @click="search" size="small" class="input">
                {{$t('search')}}
            </el-button>
            <el-button icon="el-icon-tickets" size="small" type="success" @click="openInvoice">{{$t('receipt')}}
            </el-button>
            <div style="margin-top: 20px;">
                <el-button type="text" icon="el-icon-download" @click="downloadOrigin">{{$t('downloadOrigin')}}
                </el-button>
            </div> <div style="margin-top: 20px;">
            <el-button type="text" icon="el-icon-download" @click="downloadOriginCombine">{{$t('downloadOrigin')}} Combine
            </el-button>
        </div>
        </Search>
        <div class="content">
                <div class="table-wrapper">
                <el-table
                        :data="reportList"
                        row-key="id"
                        border
                        stripe
                >
                    <el-table-column prop="stockOutNumber" :label="$t('stockOut.stockOutNo')"/>
                    <el-table-column prop="stockOutDate" :label="$t('stockOut.stockOutDate')"/>
                    <el-table-column prop="customer" :label="$t('invoice.customer')"/>
                    <el-table-column prop="partsNumber" :label="$t('part.partNo')"/>
                    <el-table-column :label="$t('part.description')" prop="partsDescription">
                    </el-table-column>
                    <el-table-column prop="applyQuantity" :label="$t('invoice.qty')"/>
                    <el-table-column prop="outQuantity" :label="$t('invoice.oQty')"/>
                    <el-table-column v-if="showUnit" prop="hostNumber" :label="$t('part.unit')"/>
                    <el-table-column v-if="showUnit" prop="systemName" :label="$t('part.system')"/>
                    <el-table-column v-if="urlAvailible('sale-price')" prop="salePrice"
                                     :label="$t('part.salesPrice')">
                        <template slot-scope="scope">
                            <span>{{scope.row.partSalePrice | money}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column
                            prop="invoiceOrNot"
                            :label="$t('stockIn.status')"
                    >
                        <template slot-scope="scope">
                            {{['Uninvoiced','Invoiced'][scope.row.invoiceOrNot]}}
                        </template>
                    </el-table-column>
                </el-table>
                <div class="page">
                    <el-pagination
                            background
                            :page-size="pageSize"
                            @current-change="changePage1"
                            layout="prev, pager, next"
                            :total="total"></el-pagination>
                </div>
            </div>
        </div>
        <el-dialog
                :title="$t('invoice.invoice')"
                :visible.sync="dialogVisible"
                width="50%"
        >
            <el-form ref="form" :model="invoice" :rules="rule" label-width="140px">
                <el-form-item :label="$t('part.qty')" prop="outQuantity">
                    <el-input v-model="invoice.outQuantity" :placeholder="$t('part.qty')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('part.salesPrice')" prop="partSalePrice">
                    <el-input v-model="invoice.partSalePrice" :placeholder="$t('part.salesPrice')"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false">{{$t('cancel')}}</el-button>
            <el-button type="primary" @click="submitForm">{{$t('confirm')}}</el-button>
          </span>
        </el-dialog>
        <el-dialog
                :title="$t('receipt')"
                :visible.sync="dialogVisible1"
                width="30%"
                style="text-align: left"
        >
            <el-card class="box-card" style="margin-bottom: 10px;">
                <div slot="header" class="clearfix">
                    <span>{{$t('receiptInfo')}}</span>
                </div>
                <div>{{$t('invoice.startTime')}}:{{time ? time[0] : ''}}</div>
                <div>{{$t('invoice.endTime')}}:{{time ? time[1] : ''}}</div>
                <div>{{$t('invoice.customer')}}:{{customer}}</div>
                <div>{{$t('invoice.factor')}}:{{coefficient}}</div>
            </el-card>
            <el-form ref="form1" :model="receipt" label-width="80px">
                <el-form-item :label="$t('invoiceNumber')">
                    <el-input v-model="receipt.invoiceNumber" :placeholder="$t('invoiceNumber')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('invoiceDate')">
                    <el-date-picker v-model="receipt.invoiceDate"
                                    value-format="yyyy-MM-dd"
                                    type="date"
                                    :placeholder="$t('invoiceDate')"></el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('woInvoice.currency')">
                    <el-input v-model="receipt.exchangeRate" :placeholder="$t('woInvoice.currency')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('woInvoice.paymentNoticeNo')">
                    <el-input v-model="receipt.paymentNoticeNo" :placeholder="$t('woInvoice.paymentNoticeNo')"></el-input>
                </el-form-item>
                <el-form-item :label="$t('woInvoice.pjbDate')">
                    <el-date-picker v-model="receipt.pjbDate" :placeholder="$t('woInvoice.pjbDate')" value-format="yyyy-MM-dd"></el-date-picker>
                </el-form-item>
                <el-form-item :label="$t('woInvoice.item')">
                    <el-input v-model="receipt.item" :placeholder="$t('woInvoice.item')"></el-input>
                </el-form-item>
                <el-form-item label="PPN">
                    <el-input value="10%"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible1 = false">{{$t('cancel')}}</el-button>
            <el-button type="primary" @click="submitForm1">{{$t('confirm')}}</el-button>
          </span>
        </el-dialog>
    </div>
</template>

<script>
    import Crumb from '../../components/common/crumb'
    import Search from '../../components/common/search'
    import {getInvoiceRecipt, deleteInvoice, modifyInvoiceRecipt, addIdrInvoice, getReport} from "../../api/service";
    import {getSpecCustomer} from "../../api/customer";
    import mixins from '../../util/mixins'
    import authMixins from '../../util/authMixins'
    import {ERROR_OK} from "../../util/config";
    import {mapGetters} from 'vuex'
    import {baseURL} from "../../util";


    export default {
        name: "report",
        mixins: [mixins, authMixins],
        props: {
            belongModule: {
                type: Number,
            },
        },
        data() {
            return {
                total1: 0,
                pageNum1: 1,
                type: true,
                showType: true,
                time:[],
                coefficient: '',
                customer: '',
                reportList: [],
                reportList1: [],
                showUnit: false,
                customerList: [],
                dialogVisible: false,
                dialogVisible1: false,
                rule: {
                    outQuantity: [{required: true, message: '数量不能为空'}],
                    partSalePrice: [{required: true, message: '价格不能为空'}]
                },
                receipt: {
                    invoiceNumber: '',
                    invoiceDate: '',
                    exchangeRate: '',
                    paymentNoticeNo:'',
                    pjbDate:'',
                    item:'',
                },
                invoice: {
                    id: '',
                    outQuantity: '',
                    partSalePrice: ''
                }
            }
        },
        filters: {
            money(num) {
                return num && num.toString()
                    .replace(/^\d+/g, (m) => m.replace(/(?=(?!^)(\d{3})+$)/g, ','))
            }
        },
        computed: {
            ...mapGetters(['auth'])
        },
        created() {
            this._getReport();
            this.getCustomerList()
        },
        mounted() {
            this.$nextTick(() => {
                import('../../util/pdf.js').then(model => {
                    this.pdf = model.default;
                })
            })
        },
        methods: {
            changePage1(page) {
                this.pageNum = page;
                this._getReport()
            },
            async submitForm1() {
                const {
                    invoiceNumber,
                    invoiceDate,
                    exchangeRate,
                    paymentNoticeNo,
                    pjbDate,
                    item,
                } = this.receipt;
                if(!this.time){
                    this.time = []
                }
                if (!this.customer && !this.time.length) {
                    this.$message.error('客户和日期不能为空')
                } else {
                    const {status, msg} = await addIdrInvoice({
                        invoiceNumber,
                        invoiceDate,
                        exchangeRate,
                        paymentNoticeNo,
                        pjbDate,
                        item,
                        customer: this.customer,
                        coefficient: this.coefficient,
                        startDate: this.time[0],
                        endDate: this.time[1],
                        belongModule: this.belongModule
                    });
                    if (status === ERROR_OK) {
                        this.$message.success(this.$t('addSuccess'));
                        this._getReport();
                        this.clear1()
                    } else {
                        this.$message.error(msg)
                    }
                }
                this.dialogVisible1 = false
            },
            clear1() {
                this.receipt = {
                    invoiceDate: '',
                    invoiceNumber: '',
                    exchangeRate: '',
                    paymentNoticeNo:'',
                    pjbDate:'',
                    item:'',
                }
            },
            submitForm() {
                this.$refs.form.validate(async valid => {
                    if (valid) {
                        const {status, msg} = await modifyInvoiceRecipt(this.invoice);
                        if (status === ERROR_OK) {
                            this.$message.success(this.$t('modifySuccess'));
                            this._getReport()
                            this.clear();
                        } else {
                            this.$message.error(msg)
                        }
                        this.dialogVisible = false;
                    }
                })
            },
            clear() {
                this.invoice = {
                    id: '',
                    outQuantity: '',
                    partSalePrice: ''
                }
            },
            edit(row) {
                this.dialogVisible = true;
                this.invoice = {
                    id: row.id,
                    partSalePrice: row.partSalePrice,
                    outQuantity: row.outQuantity
                }
            },
            openInvoice() {
                this.dialogVisible1 = true
            },
            deleteCheck(row) {
                this.$confirm(this.$t('shouldDelete'), this.$t('delete') + '?', {
                    confirmButtonText: this.$t('confirm'),
                    cancelButtonText: this.$t('cancel')
                }).then(async () => {
                    const {status} = await deleteInvoice(row.id);
                    if (status === ERROR_OK) {
                        this.reportList.splice(this.reportList.findIndex(item => item.id === row.id), 1);
                        this.$message.success(this.$t('deleteSuccess'))
                    }
                }).catch(() => {
                    this.$message.info(this.$t('operateCancel'));
                })
            },
            async getCustomerList() {
                const {status, data} = await getSpecCustomer();
                if (status === ERROR_OK) {
                    this.customerList = data
                }
            },
            search() {
                this.pageNum = 1;
                this._getReport();
            },
            async _getReport() {
                const showOrNot = this.urlAvailible('invoice-price-show') ? 1 : 0;
                const {customer, coefficient} = this;
                const {status, data} = await getInvoiceRecipt({
                    startDate: this.time ? this.time[0]:'',
                    endDate: this.time ? this.time[1] : '',
                    customer,
                    coefficient,
                    showOrNot,
                    belongModule: this.belongModule,
                    pageNum: this.pageNum
                });
                if (status === ERROR_OK) {
                    this.reportList = data.list;
                    this.total = data.total
                } else {
                    this.$notify.warning(this.$t('noData'));
                    this.reportList = []
                }
            },
            getInvoice() {
                this._getReport();
                let body = [
                    [
                        {text: 'No', alignment: 'center'},
                        {text: 'Part No', alignment: 'center'},
                        {text: 'description', colSpan: 2, style: 'tableHeader', alignment: 'center'},
                        {},
                        // {},
                        {text: 'Rate', style: 'tableHeader', alignment: 'center'},
                        {text: 'Qty', colSpan: 2, style: 'tableHeader', alignment: 'center'},
                        {},
                        {text: 'Line Total', style: 'tableHeader', alignment: 'center'},
                    ],
                    [
                        {text: '序号', style: 'tableHeader', alignment: 'center'},
                        {text: '配件编号', style: 'tableHeader', alignment: 'center'},
                        {text: '中文描述', style: 'tableHeader', alignment: 'center'},
                        {text: '英文描述', style: 'tableHeader', alignment: 'center'},
                        // {text: '主机型号', style: 'tableHeader', alignment: 'center'},
                        {text: '单价', style: 'tableHeader', alignment: 'center'},
                        {text: '数量', style: 'tableHeader', alignment: 'center'},
                        {text: '单位', style: 'tableHeader', alignment: 'center'},
                        {text: '总计', style: 'tableHeader', alignment: 'center'}
                    ],
                    // [{text: 'Service Item',colSpan:4, style: 'tableHeader', alignment: 'left'},{},{},{},{text: 'Service Fee',colSpan:4, style: 'tableHeader', alignment: 'left'},{},{},{}]
                ];
                const mainBody = this.reportList.map((item, index) => {
                    return [
                        {text: index + 1, style: 'text'},
                        {text: item.partsNumber, style: 'text'},
                        {text: item.denomination, style: 'text'},
                        {text: item.designation, style: 'text'},
                        {text: item.salePrice, style: 'text'},
                        {text: item.depleteNum, style: 'text'},
                        {text: 'pc', style: 'text'},
                        {text: item.salePrice * 100 * item.depleteNum / 100, style: 'text'}
                    ]
                });
                body = body.concat(mainBody);
                let total = 0;
                this.reportList.forEach(item => {
                    total += item.salePrice
                });

                let doc = {
                    filename: 'QO',
                    pageSize: 'LEGAL',
                    pageMargins: [10, 200, 10, 60],
                    header: [
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '70%',
                                    text: [
                                        {
                                            text: 'PT INDONESIA EQUIPMENT LINE\n',
                                            style: 'header'
                                        },
                                        {
                                            text: "Leading in Service Innovation\n",
                                            style: 'subTitle'
                                        },
                                        ' No.17-18 Blok A, Ruko Inkopal Kelapa Gading \n',
                                        ' Jl. Boulevard Barat Raya Jakarta Utara 14240 Indonesia \n',
                                        ' Tel: 0800-1581212'
                                    ],

                                },
                                {
                                    width: '*',
                                    text: 'Invoice',
                                    style: 'title',
                                    alignment: 'right'
                                }
                            ],
                        },
                        {
                            margin: [20, -10, 0, 20],
                            columns: [
                                {
                                    width: 100,
                                    text: `Bill To:${this.customer}\n`
                                },
                                {
                                    width: '60%',
                                    text: [
                                        "BUT HEBEI RESEARCH INSTITUTE OF CONSTRUCTION & GEOTECHNICAL INVESTIGATION CO,LTD \n",
                                        'THE CITY TOWER 12TH FLOOR UNIT 1N,JL,MH.THAMEIN NO 81,\nMENTENG,JAKARTA PUSAT\n',

                                    ]
                                },
                                {
                                    width: '*',
                                    text: [
                                        `Date: ${this.time[0]}-${this.time[1]}\n`,
                                        `Quotation: \n`,
                                        `SO/WO/PO : \n`,
                                        'Surat Jalan: \n',
                                        "Invoice:\n",
                                        'Customer Code:\n',
                                        "Faktur pajak No:\n"
                                    ]
                                }
                            ]
                        }
                    ],
                    content: [
                        {
                            layout: 'lightHorizontalLines',
                            alignment: 'center',
                            table: {
                                headerRows: 2,
                                // keepWithHeaderRows: 1,
                                body: body
                            }
                        },
                        {
                            margin: [20, 20, 20, 20],
                            columns: [
                                {
                                    width: '50%',
                                    text: [
                                        ' Make all checks payable to\n',
                                        'A/N: PT. INDONESIA EQUIPMENT LINE\n',
                                        'NO.: 0653700722\n',
                                        'BANK CENTRAL ASIA KCU KELAPA GADING'
                                    ]
                                },
                                {
                                    width: '*',
                                    text: [
                                        `Payment: ${total}\n`,
                                        {
                                            text: 'Value added Tax 10%\n',
                                            alignment: 'left',
                                        },
                                        `Total: ${total * 110 / 100}\n`,
                                    ]
                                }
                            ]
                        }
                    ],
                    footer: [
                        {
                            text: 'If you have any questions or concerns, please contact 0800-1581212',
                            width: '100%',
                            alignment: 'center'
                        },
                        {text: 'THANK YOU FOR YOUR BUSINESS! ', width: '100%', alignment: 'center'}
                    ],

                    defaultStyle: {
                        font: 'msyh'
                    },

                    styles: {
                        tableHeader: {
                            fontSize: 10
                        },
                        text: {
                            fontSize: 10
                        },
                        header: {
                            fontSize: 10,
                            bold: true
                        },
                        title: {
                            fontWeight: 'light',
                            fontSize: 25,
                            bold: false
                        },
                        subTitle: {
                            fontSize: 12,
                            bold: true,
                            italic: true
                        }
                    }

                }
                this.pdf.open(doc);
            },
            downloadOrigin() {
                const startTime = this.time && this.time.length ? this.time[0] : ''
                const endTime = this.time && this.time.length ? this.time[1] : ''
                const showOrNot = this.urlAvailible('invoice-price-show') ? 1 : 0;
                window.open(baseURL + `/parts_stock_out_invoice/manage/export_original_invoice_excel.file?startTime=${startTime}&endTime=${endTime}&customer=${this.customer}&coefficient=${this.coefficient}&integration=${this.showType ? 1 : 2}&belongModule=${this.belongModule}&showOrNot=${showOrNot}`)
            },
            downloadOriginCombine() {
                const startTime = this.time && this.time.length ? this.time[0] : ''
                const endTime = this.time && this.time.length ? this.time[1] : ''
                const showOrNot = this.urlAvailible('invoice-price-show') ? 1 : 0;
                window.open(baseURL + `/parts_stock_out_invoice/manage/export_original_summary_invoice_excel.file?startTime=${startTime}&endTime=${endTime}&customer=${this.customer}&coefficient=${this.coefficient}&integration=${this.showType ? 1 : 2}&belongModule=${this.belongModule}&showOrNot=${showOrNot}`)
            }
        },
        watch: {
            type() {
                this.pageNum = 1
            }
        },
        components: {
            Crumb, Search
        }
    }
</script>

<style scoped lang="scss">
    @import "../../css/mixins";

    .content {
        @include content
    }
</style>